package com.see.network.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Properties;

import com.see.network.api.HtmlReader;

public class HtmlReaderImpl implements HtmlReader {
	private ProxyManager proxyManager;
	private HttpURLConnection conn;

	public String readHtml(String urlString, boolean proxyEnable) {

		proxyManager = new ProxyManager(proxyEnable);
		StringBuffer document = new StringBuffer();
		// initialize connection
		conn = null;
		try {
			URL url = new URL(urlString);

			conn = (HttpURLConnection) url.openConnection();
			InputStream is = conn.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader reader = new BufferedReader(isr);
			String line = null;
			while ((line = reader.readLine()) != null)
				document.append(line);
			is.close();
			isr.close();
			reader.close();

			String htmlContent = replaceHtmlEntities(document.toString());

			return htmlContent;

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			conn.disconnect();
		}
		return null;
	}

	private String replaceHtmlEntities(String string) {

		if (string.contains("&amp;")) {
			string = string.replaceAll("&amp;", "&");
		}

		return string;
	}

}
